package vn.sms.lazylove;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import vn.sms.lazylove.database.DataStore;
import vn.sms.lazylove.object.OneSMS;
import vn.sms.lazylove.object.SchedulerSMSItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View.OnClickListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.ads.AdView;

public class CreateSmsActivity extends Activity {

	private Activity mActivity;
	private Context mContext;
	private Bundle b;
	private String listphone;
	TextView txt_select_week, txt_select_time_from, txt_select_time_to,
			txt_select_sms, txt_select_contact, txt_select_list_contact;
	Button btnBack, btnRight, btnCreate, btnRevert, btnCancel;
	RelativeLayout rlt_timefrom, rlt_timeto, rlt_repeatrandom, rlt_messagesend,
			rlt_contactsend;
	ImageView btnOn, btnOff;
	DataStore mDataStore;
	SchedulerSMSItem smsItem;
	List<SchedulerSMSItem> listScheduler;
	Calendar dateTime;
	private AlarmManagerBroadcastReceiver alarm;
	SimpleDateFormat dateFormatter;
	private ProgressDialog mProgressBar = null;
	private static final int DIALOG_WEEK = 1;
	private static final int DIALOG_TIME_FROM = 2;
	private static final int DIALOG_TIME_TO = 7;
	private static final int DIALOG_DATE = 3;
	private static final int RESURT_OK = 4;
	private static final int RESURT_NO = 5;
	private static final int RESURT_NO_CONTACT = 6;	
	AdView adView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_create_sms);
		mActivity = this;
		mContext = this;
		mDataStore = DataStore.getInstance();
		dateTime = Calendar.getInstance();
		dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
		alarm = new AlarmManagerBroadcastReceiver();
		b = getIntent().getExtras();
		if (b != null) {
			listphone = b.getString("phone");
		}
		btnBack = (Button) findViewById(R.id.btn_left);
		btnRight = (Button) findViewById(R.id.btn_right);
		btnRight.setBackgroundResource(R.drawable.selector_button_help);
		TextView txt_title = (TextView) findViewById(R.id.txt_title);
		txt_title.setText(getString(R.string.txt_setting_sms));
		btnOn = (ImageView) findViewById(R.id.on_btn);
		btnOff = (ImageView) findViewById(R.id.off_btn);
		txt_select_week = (TextView) findViewById(R.id.txt_select_week);
		txt_select_time_from = (TextView) findViewById(R.id.txt_select_time_from);
		txt_select_time_to = (TextView) findViewById(R.id.txt_select_time_to);
		txt_select_sms = (TextView) findViewById(R.id.txt_select_sms);
		txt_select_contact = (TextView) findViewById(R.id.txt_select_contact);
		txt_select_list_contact = (TextView) findViewById(R.id.txt_select_list_contact);
		List<SchedulerSMSItem> listSMS = mDataStore.getListSMSScheduler();
		if (listSMS.size() < 1) {
			txt_select_list_contact.setText(listphone);
			btnOn.setVisibility(View.GONE);
			btnOff.setVisibility(View.VISIBLE);
		} else {
			smsItem = listSMS.get(0);
			String[] time = smsItem.time.split("-");
			txt_select_week.setText(smsItem.week);
			txt_select_time_from.setText(time[0]);
			txt_select_time_to.setText(time[1]);
			txt_select_sms.setText(smsItem.message);
			if (listphone != null)
				txt_select_list_contact.setText(listphone);
			else {
				txt_select_list_contact.setText(smsItem.phone);
			}
			if (smsItem.status == 1) {
				btnOff.setVisibility(View.GONE);
				btnOn.setVisibility(View.VISIBLE);
			} else {
				btnOn.setVisibility(View.GONE);
				btnOff.setVisibility(View.VISIBLE);
			}

		}
		rlt_timefrom = (RelativeLayout) findViewById(R.id.rlt_timefrom);
		rlt_timeto = (RelativeLayout) findViewById(R.id.rlt_timeto);
		rlt_repeatrandom = (RelativeLayout) findViewById(R.id.rlt_repeatrandom);
		rlt_messagesend = (RelativeLayout) findViewById(R.id.rlt_messagesend);
		rlt_contactsend = (RelativeLayout) findViewById(R.id.rlt_contactsend);

		rlt_repeatrandom.setOnClickListener(onClickWeekListener);
		rlt_timefrom.setOnClickListener(onClickTimeFromListener);
		rlt_timeto.setOnClickListener(onClickTimeToListener);
		rlt_messagesend.setOnClickListener(onClickPatentListener);
		rlt_contactsend.setOnClickListener(onClickContactListener);

		txt_select_week.setOnClickListener(onClickWeekListener);
		txt_select_time_from.setOnClickListener(onClickTimeFromListener);
		txt_select_time_to.setOnClickListener(onClickTimeToListener);
		txt_select_sms.setOnClickListener(onClickPatentListener);
		txt_select_contact.setOnClickListener(onClickContactListener);

		btnCreate = (Button) findViewById(R.id.btn_create);
		btnCreate.setOnClickListener(onClickCreateListener);
		btnBack.setOnClickListener(onClickBackListener);
		btnOn.setOnClickListener(onClickOnListener);
		btnOff.setOnClickListener(onClickOffListener);
		btnRight.setOnClickListener(onClickHelperListener);

		btnRevert = (Button) findViewById(R.id.btn_revert);
		btnRevert.setVisibility(Button.GONE);
		btnCancel = (Button) findViewById(R.id.btn_cancel);
		btnRevert.setOnClickListener(onClickRevertListener);
		btnCancel.setOnClickListener(onClickBackListener);

		// ads
		// String AD_UNIT_ID_GOES_HERE = "2g9h6462fzkkv77d";
		// adView = new AdView(this, AdSize.BANNER, AD_UNIT_ID_GOES_HERE);
		// LinearLayout layout = (LinearLayout) findViewById(R.id.linear_ads);
		// layout.addView(adView);
		// AdRequest adRequest = new AdRequest();
		// adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
		// adView.loadAd(adRequest);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1) {
			if (resultCode == RESULT_OK) {
				String result = data.getStringExtra("phone");
				txt_select_list_contact.setText(result);
			}
			if (resultCode == RESULT_CANCELED) {
				txt_select_list_contact.setText("");
			}
		}
		if (requestCode == 2) {
			if (resultCode == RESULT_OK) {
				String result = data.getStringExtra("sms");
				txt_select_sms.setText(result);
			}
			if (resultCode == RESULT_CANCELED) {
				txt_select_list_contact.setText("");
			}
		}
	}

	public void startRepeatingTimer() {
		if (alarm != null) {
			alarm.SetAlarm(mContext, smsItem);
			try {
				OneSMS os = new OneSMS(1, 100, 0);
				mDataStore.updateOneSMS(os);
			} catch (Exception ex) {
			}
		} else {
			Toast.makeText(mContext, "Alarm is null", Toast.LENGTH_SHORT)
					.show();
		}
	}

	public void cancelRepeatingTimer() {
		if (alarm != null) {
			alarm.CancelAlarm(mContext);
		} else {
			Toast.makeText(mContext, "Alarm is null", Toast.LENGTH_SHORT)
					.show();
		}
	}

	public void onetimeTimer() {
		if (alarm != null) {
			alarm.setOnetimeTimer(mContext, smsItem);
		} else {
			Toast.makeText(mContext, "Alarm is null", Toast.LENGTH_SHORT)
					.show();
		}
	}

	OnClickListener onClickRevertListener = new OnClickListener() {

		public void onClick(View v) {
			btnOn.setVisibility(View.GONE);
			btnOff.setVisibility(View.VISIBLE);
			if (mDataStore.updateStatusScheduler(smsItem)) {
				cancelRepeatingTimer();
			}
		}
	};

	OnClickListener onClickHelperListener = new OnClickListener() {

		public void onClick(View v) {
			Intent myH = new Intent(mContext, HelperActivity.class);
			startActivity(myH);
		}
	};

	OnClickListener onClickOnListener = new OnClickListener() {

		public void onClick(View v) {
			btnOn.setVisibility(View.GONE);
			btnOff.setVisibility(View.VISIBLE);
			if (mDataStore.updateStatusScheduler(smsItem)) {
				cancelRepeatingTimer();
			}
		}
	};

	OnClickListener onClickOffListener = new OnClickListener() {

		public void onClick(View v) {
			btnOff.setVisibility(View.GONE);
			btnOn.setVisibility(View.VISIBLE);
			if (mDataStore.updateStatusScheduler(smsItem)) {
				// cancelRepeatingTimer();
				startRepeatingTimer();
			}
		}
	};

	OnClickListener onClickBackListener = new OnClickListener() {

		public void onClick(View v) {
			onBackPressed();
		}
	};

	OnClickListener onClickDateListener = new OnClickListener() {

		public void onClick(View v) {
			showDialog(DIALOG_DATE);
		}
	};
	OnClickListener onClickTimeFromListener = new OnClickListener() {

		public void onClick(View v) {
			showDialog(DIALOG_TIME_FROM);
		}
	};
	OnClickListener onClickTimeToListener = new OnClickListener() {

		public void onClick(View v) {
			showDialog(DIALOG_TIME_TO);
		}
	};
	OnClickListener onClickWeekListener = new OnClickListener() {

		public void onClick(View v) {
			showDialog(DIALOG_WEEK);
		}
	};
	OnClickListener onClickContactListener = new OnClickListener() {

		public void onClick(View v) {
			Intent i = new Intent(mContext, ContactActivity.class);
			Bundle b = new Bundle();
			b.putInt("mStartMode", 0);
			i.putExtras(b);
			startActivityForResult(i, 1);
		}
	};
	OnClickListener onClickPatentListener = new OnClickListener() {

		public void onClick(View v) {
			Intent i = new Intent(mContext, SMSPatentActivity.class);
			startActivityForResult(i, 2);
		}
	};

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			hideLoadingControl();
			switch (msg.what) {
			case RESURT_OK:
				btnOff.setVisibility(View.GONE);
				btnOn.setVisibility(View.VISIBLE);
				// cancelRepeatingTimer();
				startRepeatingTimer();
				Toast.makeText(mContext,
						getString(R.string.txt_cai_dat_thanh_cong),
						Toast.LENGTH_SHORT).show();
				break;
			case RESURT_NO:
				Toast.makeText(mContext,
						getString(R.string.txt_cai_dat_that_bai),
						Toast.LENGTH_SHORT).show();
				break;
			case RESURT_NO_CONTACT:
				Toast.makeText(mContext,
						getString(R.string.txt_select_contact),
						Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	OnClickListener onClickCreateListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			showLoadingControl();
			Thread dataInitializationThread = new Thread() {
				public void run() {
					String phone = txt_select_list_contact.getText().toString();
					String message = txt_select_sms.getText().toString();
					String week = txt_select_week.getText().toString();
					String time = txt_select_time_from.getText().toString()
							+ "-" + txt_select_time_to.getText().toString();
					try {
						if (!phone.equals("")) {
							SchedulerSMSItem s = new SchedulerSMSItem();
							s.id = 1;
							s.name = "SMS";
							s.phone = phone;
							s.message = message;
							s.week = week;
							s.time = time;
							s.status = 1;
							boolean checkFlag = false;
							if (mDataStore.getListSMSScheduler().size() < 1) {
								checkFlag = mDataStore.addSMSScheduler(s);
							} else {
								checkFlag = mDataStore.updateScheduler(s);
							}
							if (checkFlag) {
								// Intent intent = new Intent(mActivity,
								// ListSchedulerActivity.class);
								// startActivity(intent);
								mHandler.sendEmptyMessage(RESURT_OK);
							} else {
								mHandler.sendEmptyMessage(RESURT_NO);
							}
						} else {
							mHandler.sendEmptyMessage(RESURT_NO_CONTACT);
						}
					} catch (Exception ex) {
						mHandler.sendEmptyMessage(RESURT_NO);
					}
				};
			};
			dataInitializationThread.start();
		}
	};

	private void showLoadingControl() {
		mProgressBar = ProgressDialog.show(mActivity, "",
				getString(R.string.loading_default), true);

	}

	private void hideLoadingControl() {
		if (mProgressBar != null && mProgressBar.isShowing())
			mProgressBar.dismiss();

	}

	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		final CharSequence[] items = { getString(R.string.txt_thu_2),
				getString(R.string.txt_thu_3), getString(R.string.txt_thu_4),
				getString(R.string.txt_thu_5), getString(R.string.txt_thu_6),
				getString(R.string.txt_thu_7), getString(R.string.txt_chu_nhat) };
		final boolean[] itemsChecked = new boolean[items.length];
		switch (id) {
		case DIALOG_DATE:
			return new DatePickerDialog(this, new OnDateSetListener() {
				@Override
				public void onDateSet(DatePicker view, int year,
						int monthOfYear, int dayOfMonth) {
					dateTime.set(year, monthOfYear, dayOfMonth);
					txt_select_time_to.setText(dateFormatter.format(dateTime
							.getTime()));
				}
			}, dateTime.get(Calendar.YEAR), dateTime.get(Calendar.MONTH),
					dateTime.get(Calendar.DAY_OF_MONTH));
		case DIALOG_TIME_FROM:
			return new TimePickerDialog(this, new OnTimeSetListener() {
				@Override
				public void onTimeSet(TimePicker view, int hour, int minute) {
					txt_select_time_from.setText(new StringBuilder()
							.append(pad(hour)).append(":").append(pad(minute)));
					if (minute < 50) {
						txt_select_time_to.setText(new StringBuilder()
								.append(pad(hour)).append(":")
								.append(pad(minute + 10)));
					} else {
						txt_select_time_to.setText(new StringBuilder()
								.append(pad(hour)).append(":")
								.append(pad(minute + 1)));
					}
				}
			}, dateTime.get(Calendar.HOUR_OF_DAY), dateTime
					.get(Calendar.MINUTE), false);
		case DIALOG_TIME_TO:
			return new TimePickerDialog(this, new OnTimeSetListener() {
				@Override
				public void onTimeSet(TimePicker view, int hour, int minute) {
					try {
						String[] timeFrom = txt_select_time_from.getText()
								.toString().split(":");
						int timeTemp = Integer.parseInt(timeFrom[0]) * 60
								+ Integer.parseInt(timeFrom[1]);
						int timeTemp2 = hour * 60 + minute;
						if (timeTemp2 > timeTemp) {
							txt_select_time_to.setText(new StringBuilder()
									.append(pad(hour)).append(":")
									.append(pad(minute)));
						} else {
							Toast.makeText(mContext,
									"Note: Time To > time From",
									Toast.LENGTH_LONG).show();
						}
					} catch (Exception ex) {
						Toast.makeText(mContext, "Erro!", Toast.LENGTH_LONG)
								.show();
					}
				}
			}, dateTime.get(Calendar.HOUR_OF_DAY),
					dateTime.get(Calendar.MINUTE), false);
		case DIALOG_WEEK:
			return new AlertDialog.Builder(this)
					.setIcon(R.drawable.ic_launcher)
					.setTitle(R.string.txt_week_title)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									StringBuilder sb = new StringBuilder();
									int k = 0;
									for (int i = 0; i < items.length; i++) {
										if (itemsChecked[i]) {
											k++;
											if (k != 1)
												sb.append(",");
											sb.append(items[i]);
										}
									}
									txt_select_week.setText(sb);
								}
							})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							})
					.setMultiChoiceItems(items, itemsChecked,
							new DialogInterface.OnMultiChoiceClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which, boolean isChecked) {
								}
							}).create();
		}

		return null;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_create, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_sendsms:
			Intent myI = new Intent(mContext, SendSMSActivity.class);
			startActivity(myI);
			break;
		default:
			finish();
			break;
		}
		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		// cancelNotification();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// cancelNotification();
		// if (adView != null) {
		// adView.destroy();
		// }
	}
}